import 'package:flutter/material.dart';
// 消息弹框
import 'package:fluttertoast/fluttertoast.dart';

import '../../services/ScreenAdapter.dart';
import '../../config/Config.dart';
import '../../widget/MyButton.dart';
import '../../services/CartServices.dart';
import 'CartNum.dart';

// provider
import 'package:provider/provider.dart';
import '../../provider/Cart.dart';

// 广播
import '../../services/EventBus.dart';

// 商品详情页 TabBarView--> 商品
class ProductContentFirst extends StatefulWidget {
  final Object contentObj;

  ProductContentFirst({this.contentObj});

  @override
  State<StatefulWidget> createState() =>
      ProductContentFirstState(contentObj: contentObj);
}

class ProductContentFirstState extends State<ProductContentFirst>
    with AutomaticKeepAliveClientMixin {
  //  缓存
  @override
  bool get wantKeepAlive => true;

  List attrList = [];
  Map contentObj;
  var state; //  接收showModalBottomSheet中setState
  String checkedAttr = ''; //已选的属性
  int count = 1;  //因为服务器没有数据，自定义默认数据已选择1件
  var actionBottomEventBus;  // 底部弹框广播事件监听
  var actionCountEventBus;   // count广播事件监听
  var cartProvider;   // provider的cart
  ProductContentFirstState({this.contentObj});

  @override
  Widget build(BuildContext context) {
    this.cartProvider = Provider.of<Cart>(context);

    return Container(
        padding: EdgeInsets.all(10),
        child: ListView(
          children: [
            // 图片
            AspectRatio(
              aspectRatio: 16 / 12,
              child: Image.network(
                  '${Config.domain + contentObj['pic'].replaceAll('\\', '/')}',
                  fit: BoxFit.fill),
            ),
            SizedBox(height: 20),

            // 标题
            Text('${contentObj['title']}',
                style: TextStyle(fontSize: 18, color: Colors.black87)),
            SizedBox(height: 20),

            // 描述
            Text('${contentObj['sub_title']}',
                style: TextStyle(color: Colors.black54, fontSize: 14)),
            SizedBox(height: 20),

            // 价格
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Container(
                  child: Row(
                    children: [
                      Text('特价：'),
                      Text('￥${contentObj['old_price']}',
                          style: TextStyle(color: Colors.red, fontSize: 20)),
                    ],
                  ),
                ),
                Container(
                  child: Row(
                    children: [
                      Text('原价：'),
                      Text('￥${contentObj['price']}',
                          style: TextStyle(
                            color: Colors.black38,
                            decoration: TextDecoration.lineThrough,
                          ))
                    ],
                  ),
                )
              ],
            ),
            SizedBox(height: 20),

            // 已选
            attrList.length > 0 ? Column(
              children: [
                InkWell(
                  child: Row(children: [
                    Text('已选：'),
                    Text(checkedAttr),
                    Text('，$count件')
                  ]),
                  onTap: () {
                    _attrBottomSheet();
                  },
                ),
                Divider(),
                SizedBox(height: 10),
              ],
            ) : Container(
              height: 0,
            ),

            // 运费
            Row(
              children: [
                Text('运费：'),
                Text('免费'),
              ],
            ),
            Divider(),
            SizedBox(height: ScreenAdapter.height(100)),
          ],
        ));
  }

  @override
  initState() {
    super.initState();
    _initAttr();

    // 已选的属性
    _showChecked();

    // 监听广播
    // 如果有属性
    if (attrList.length > 0) {
      // 监听点击加入购物车事件，
      this.actionBottomEventBus = eventBus.on<ProductContentEvent>().listen((event) {
        // 弹出底部弹框
        this._attrBottomSheet();
      });

      // 监听count变化
      this.actionCountEventBus = eventBus.on<ProductContentFirstCountEvent>().listen((event) {
        this.setState(() {
          // 修改count
          count = count + event.addOrSub;

          // 修改属性值
          _showChecked();
        });
      });
    }
  }

  // 生命周期销毁
  dispose() {
    super.dispose();
    // 销毁底部弹框广播事件监听
    if (this.actionBottomEventBus != null) {
      this.actionBottomEventBus.cancel();
    }

    // 销毁count广播事件监听
    if (this.actionCountEventBus != null) {
      this.actionCountEventBus.cancel();
    }
  }

  // 已选的属性
  _showChecked() {
    var checkedAttrList = [];
    for (var i = 0; i < attrList.length; i++) {
      List list = attrList[i]['list'];

      // 选中的属性
      for (var j = 0; j < list.length; j++) {
        if (list[j]['checked']) {
          checkedAttrList.add(list[j]['title']);
        }
      }
    }
    this.setState(() {
      checkedAttr = checkedAttrList.join('，');
    });
  }

  //  底部菜单列表
  _attrBottomSheet() {
    // showModalBottomSheet是另一个路由, 在里面使用this.setState不能改变值
    return showModalBottomSheet(
        context: context,
        builder: (context) {
          return StatefulBuilder(
            // 使用StatefulBuilder将setState值传给showModalBottomSheet中的组件
              builder: (context, state) {
                this.state = state; //这里的state就是setState
                return Stack(
                  children: [
                    // 属性
                    Container(
                      child: Column(
                        children: [
                          // 每个商品自己独特属性
                          ListView(
                            shrinkWrap: true,
                            padding: EdgeInsets.all(10),
                            children: _cateList(),
                          ),

                          // 数量属性
                          Container(
                            padding: EdgeInsets.all(10),
                            child: Row(
                              children: [
                                Container(
                                  margin: EdgeInsets.only(right: 10),
                                  child:Text('数量：'),
                                ),
                                CartNum(this.count),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),

                    // 底部：加入购物车， 立即购买
                    Positioned(
                      bottom: 0,
                      width: ScreenAdapter.width(750),
                      height: ScreenAdapter.height(100),
                      child: Container(
                        child: Row(
                          children: [
                            Expanded(
                                flex: 1,
                                child: MyButton(
                                    text: '加入购物车',
                                    color: Colors.red,
                                    cb: () async {
                                      // 添加商品，必须加await，此方法是异步方法 需让数据更新完毕之后进行后面操作
                                      await CartServices.addCart(this.contentObj, checkedAttr, count);

                                      // 更新购物车数据
                                      this.cartProvider.updateCartListData();

                                      // 关闭底部弹框
                                      Navigator.of(context).pop();

                                      Fluttertoast.showToast(
                                          msg: "已加入购物车",
                                          toastLength: Toast.LENGTH_SHORT,
                                          gravity: ToastGravity.CENTER,
                                      );
                                    })),
                            Expanded(
                                flex: 1,
                                child: MyButton(
                                    text: '立即购买',
                                    color: Colors.orange,
                                    cb: () {
                                      // 关闭
                                      Navigator.of(context).pop();
                                    }))
                          ],
                        ),
                      ),
                    )
                  ],
                );
              });
        });
  }

  // 每个属性, 例如 颜色，尺寸，材料
  List<Widget> _cateList() {
    // 返回属性列表
    return attrList.map((e) {
      // 每个属性
      return Wrap(
        crossAxisAlignment: WrapCrossAlignment.center,
        spacing: 10,
        runSpacing: 5,
        children: _cList(e), //属性名 和 可选属性值
      );
    }).toList();
  }

  // 每个属性名 和 它的属性可选值, 例如 颜色：红色、蓝色、白色
  List<Widget> _cList(e) {
    List<Widget> newList = [];
    List list = e['list'];
    // 属性名
    newList.add(Text('${e["cate"]}：'));
    for (var i = 0; i < list.length; i++) {
      // 属性可选值
      if (list[i]['checked']) {
        newList.add(_myBtn(
            list[i]['title'], Colors.red, Colors.white, e["cate"], list[i]));
      } else {
        newList.add(_myBtn(list[i]['title'], Colors.black12, Colors.black,
            e["cate"], list[i]));
      }
    }
    newList.add(Divider());
    // 返回列表
    return newList;
  }

  // 自定义的属性按钮
  Widget _myBtn(text, color, textColor, cate, listItem) {
    return InkWell(
      child: Chip(
        padding: EdgeInsets.all(5),
        label: Text(text, style: TextStyle(color: textColor)),
        backgroundColor: color,
      ),
      onTap: () {
        _changeAttr(cate, listItem);
      },
    );
  }

  //  点击改变checked
  _changeAttr(cate, listItem) {
    List newAttrList = attrList;
    for (var i = 0; i < newAttrList.length; i++) {
      var attrCate = newAttrList[i]['cate'];
      var attrI = newAttrList[i]['list'];
      if (attrCate == cate) {
        for (var j = 0; j < attrI.length; j++) {
          newAttrList[i]['list'][j]['checked'] = false;

          if (attrI[j] == listItem) {
            newAttrList[i]['list'][j]['checked'] = true;
          } else {
            newAttrList[i]['list'][j]['checked'] = false;
          }
        }
      }

      // 因为showModalBottomSheet是另外一个页面，将setState传给挂到state中使用
      this.state(() {
        attrList = newAttrList;

        // 改变选中的属性
        _showChecked();
      });
    }
  }

  // 初始化时候，修改数据不全的原始attr数据，给原始attr增加checked属性
  _initAttr() {
    attrList = contentObj['attr'];
    for (var i = 0; i < attrList.length; i++) {
      List list = attrList[i]['list'];
      for (var j = 0; j < list.length; j++) {
        if (j == 0) {
          attrList[i]['list']
          [j] = {"title": attrList[i]['list'][j], "checked": true};
        } else {
          attrList[i]['list']
          [j] = {"title": attrList[i]['list'][j], "checked": false};
        }
      }
    }
  }
}
